package com.sunseen.intelligencebus

import android.Manifest
import android.annotation.TargetApi
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.media.Ringtone
import android.media.RingtoneManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Vibrator
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.baidu.tts.client.SpeechSynthesizer
import com.baidu.tts.client.TtsMode
import com.sunseen.intelligencebus.base.SupportActivity
import com.sunseen.intelligencebus.common.*
import com.sunseen.intelligencebus.databinding.ActivityMainBinding
import com.sunseen.intelligencebus.home.BusMsgGotEvent
import com.sunseen.intelligencebus.riding.QrCodeRefershEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.ArrayList

class MainActivity : SupportActivity() {

    private var loginState by Preference(Preference.LOGIN_STATE, false)


    lateinit var mVibrator: Vibrator
    lateinit var mRingtone: Ringtone


    companion object {
        const val baiduTtsAppId = "15804658"
        const val baiduTtsAppkey = "ZcHECAEisjYsHV8KNWopq6jG"
        const val baiduTtsSecretKey = "SpbDPNHkZqciaxXhKybmu5qXuDZGDVXq"
        val ttsMOde = TtsMode.ONLINE
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        mVibrator = getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
        val notifyUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        mRingtone = RingtoneManager.getRingtone(this, notifyUri)
        supportActionBar!!.hide()
        DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
        if (loginState) {
            loadRootFragment(R.id.fragment_container, MainFragment.newInstance())
        } else {
            loadRootFragment(R.id.fragment_container, LoginFragment.newInstance())
        }

        val theIntent = Intent(this, BtMsgService::class.java)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(theIntent)
        } else {
            startService(theIntent)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "station"
            val channelName = "到站提醒"
            createNotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
        }

        initPermission()
        initTts()
    }

    private fun sendNotifyMsg(tipString: String) {
        val manager: NotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val notification = NotificationCompat.Builder(this, "station")
            .setContentTitle("到站提醒")
            .setContentText(tipString)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.mipmap.ic_intelligence_bus_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_intelligence_bus_launcher))
            .setAutoCancel(true)
            .build()
        manager.notify(1, notification)
    }

    private fun viberaRing() {
        mVibrator.vibrate(500)
        mRingtone.play()
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(channelId: String, channelName: String, importance: Int) {
        val channel = NotificationChannel(channelId, channelName, importance);
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBluetoothStateChange(event: BluetoothStateChangeEvent) {
        when (event.state) {
            BluetoothAdapter.STATE_ON -> {
                Toast.makeText(this, "蓝牙已打开", Toast.LENGTH_SHORT).show()
            }
            BluetoothAdapter.STATE_OFF -> {
                Toast.makeText(this, "蓝牙已关闭", Toast.LENGTH_SHORT).show()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onArriveAtStation(event: ArriveAtStationEvent) {
        val notifyStr = if (event.isAtStation) {
            "智慧公交APP提醒您:公交车已到达${event.stationName},请抓紧时间下车"
        } else {
            "智慧公交APP提醒您:公交车已到达${event.stationName},请做好准备,下一站下车"
        }
        sendNotifyMsg(notifyStr)
        speak(notifyStr)
        viberaRing()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSpeakEvent(event: SpeakEvent) {
        Log.e("test", "onSpeakEvent")
        speak("时间是一切财富中最宝贵的财富")
    }

    private var goalStationId = -1
    private var goalPrevStationId = -1

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRefreshQrcode(event: QrCodeRefershEvent) {
        if (event.stationId >= 0) {
            goalStationId = event.stationId
            goalPrevStationId = event.stationId - 1
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBusMsgGot(event: BusMsgGotEvent) {
        for (b in event.bytes) {
            if (b > 100) {
                arriveTest(b)
            }
        }
    }

    private fun arriveTest(b: Byte) {
        var curStationId = 0
        when (b) {
            111.toByte() -> curStationId = 0
            112.toByte() -> curStationId = 1
            113.toByte() -> curStationId = 2
            114.toByte() -> curStationId = 3
            115.toByte() -> curStationId = 4
            116.toByte() -> curStationId = 5
            else -> curStationId = 0
        }
        if (goalStationId > 0 && curStationId == goalStationId) {
            //提醒已到站
            notifyStation(goalStationId, false)

        } else if (goalPrevStationId > 1 && curStationId == goalPrevStationId) {
            //提醒已到前一站，下一站下车
            notifyStation(goalPrevStationId, true)
        }
    }

    private fun notifyStation(stationId: Int, isPrev: Boolean) {
        var stationName = "火车站"
        when (stationId) {
            0 -> stationName = "火车站"
            1 -> stationName = "广场站"
            2 -> stationName = "汽车站"
            3 -> stationName = "二中站"
            4 -> stationName = "应科站"
            5 -> stationName = "附医站"
        }

        val notifyStr = if (isPrev) {
            "智慧公交APP提醒您:公交车已到达$stationName,请做好准备,下一站下车"

        } else {
            "智慧公交APP提醒您:公交车已到达$stationName,请抓紧时间下车"
        }
        Log.e("test", "到站 " + stationName)
        sendNotifyMsg(notifyStr)
        viberaRing()
        speak(notifyStr)
    }


    private val mainHandler = Handler()
    private lateinit var synthesizer: NonBlockSyntherizer
    private fun initTts() {
        val params = mapOf<String, String>(SpeechSynthesizer.PARAM_VOLUME to "9")
        val listener = UiMessageListener(mainHandler)
        val initConfig = InitConfig(baiduTtsAppId, baiduTtsAppkey, baiduTtsSecretKey, ttsMOde, params, listener)
        synthesizer = NonBlockSyntherizer(this, initConfig, mainHandler)
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private fun initPermission() {
        val permissions = arrayOf(
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.MODIFY_AUDIO_SETTINGS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_SETTINGS,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )

        val toApplyList = ArrayList<String>()

        for (perm in permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm)
                // 进入到这里代表没有权限.
            }
        }
        val tmpList = arrayOfNulls<String>(toApplyList.size)
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123)
        }

    }

    /**
     * speak 实际上是调用 synthesize后，获取音频流，然后播放。
     * 获取音频流的方式见SaveFileActivity及FileSaveListener
     * 需要合成的文本text的长度不能超过1024个GBK字节。
     */
    private fun speak(text: String) {
        val result = synthesizer.speak(text)
        checkResult(result, "speak")
    }

    private fun checkResult(result: Int, method: String) {
        if (result != 0) {
            Log.e("test", "error code :$result method:$method, 错误码文档:http://yuyin.baidu.com/docs/tts/122 ")
        }
    }


}
